from flask import request
from flask import redirect
from itsdangerous import TimedJSONWebSignatureSerializer
from itsdangerous import BadSignature
from . import appid
from . import token
from functools import wraps

login_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=https%%3A%%2F%%2Fapi.boot.pw' \
            '%%2Fpre_login&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect' % appid


def token_required(fun):
    @wraps(fun)
    def inner(*args, **kargs):
        if 'auth' not in request.cookies:
            return redirect(login_url)
        else:
            auth_str = request.cookies['auth']

            try:
                s = TimedJSONWebSignatureSerializer(token)
                data = s.loads(auth_str)
            except BadSignature:
                return redirect(login_url)
        return fun(*args, **kargs)
    return inner
